package top.csy8888.ch01.common;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author CSY
 * @date 2025 - 09 - 04
 * minio工具类
 */
public class MinioUtils {
    //连接属性
    private static final String HOST = "http://127.0.0.1:9000";
    private static final String ACCOUNT = "csy";
    private static final String PASSWORD = "csy11348336";

    //minio客户端
    private static MinioClient client;

    /**
     * 初始化客户端
     */
    static{
        client = MinioClient.builder()
                //设置主机地址
                .endpoint(HOST)
                //设置账号密码
                .credentials(ACCOUNT, PASSWORD)
                .build();
    }

    /**
     * 判断桶是否创建
     * @param bucketName
     * @return
     */
    public static boolean hasBucket(String bucketName){
        try {
            //bucketExists:MinioClient对象自带的判断方法
            //BucketExistsArgs:判断参数（桶名）
            return client.bucketExists(BucketExistsArgs
                    .builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据桶名创建桶
     * @param bucketName
     */
    public static void createBucket(String bucketName){
        try{
            //makeBucket:MinioClient对象自带的桶创建方法
            //MakeBucketArgs:创建的桶参数（桶名）
            client.makeBucket(MakeBucketArgs
                    .builder()
                    .bucket(bucketName)
                    .build());
        }catch (Exception e){
            throw new RuntimeException("Create fail:"+e);
        }
    }

    /**
     *
     * @param bucketName 桶名
     * @param objectPath 对象路径
     * @param contentType 文件类型
     * @param size 文件大小
     * @param input 上传的输入流
     */
    public static void upload(String bucketName,
                              String objectPath,
                              String contentType,
                              long size,
                              InputStream input){
        try{
            client.putObject(PutObjectArgs
                    .builder()
                    .bucket(bucketName)
                    .object(objectPath)
                    .contentType(contentType)
                    //第三个参数表示上传到文件的末尾
                    .stream(input,size,-1)
                    .build());
        }catch (Exception e){
            throw new RuntimeException("Upload fail:"+e);
        }
    }
}
